<!DOCTYPE HTML>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <title>51CTO会议记录</title>
    <link rel="stylesheet" href="assets/css/vant.min.css" />
</head>

<body>
    <script src="assets/js/recorder-core.js"></script>
    <script src="assets/js/beta-amr-engine.js"></script>
    <script src="assets/js/beta-amr.js"></script>
    <script src="assets/js/wav.js"></script>
    <script src="assets/js/frequency.histogram.view.js"></script>
    <script src="assets/js/lib.fft.js"></script>
    <script src="assets/js/vue.js"></script>
    <script src="assets/js/vant.min.js"></script>
    <div id="app" class="main-box">
        <van-field v-model="group_id" placeholder="请输入钉钉群链接" style="margin-bottom: 30px;width: 300px;"></van-field>
        <div class="timecount-box" v-if="recordStatus === 0 || recordStatus === 1">{{ formatTime(time) }}</div>
        <van-button type="success" v-if="recordStatus === 0" @click="handleToStartRecord">开始录音</van-button>
        <van-button type="danger" v-else-if="recordStatus === 1" @click="handleToStopRecord">停止录音</van-button>
        <template v-else-if="recordStatus === 2">
            <van-space direction="vertical" align="center">
                <audio style="width: 300px;" controls :src="recordSrc"></audio>
                <van-button type="default" @click="handleToResetRecord">重新录制</van-button>
                <van-button type="primary" @click="handleToUploadRecord">上传文件</van-button>
            </van-space>
        </template>
    </div>
    <script>
        const app = Vue.createApp({
            data() {
                return {
                    group_id: '', // 群链接
                    recordStatus: 0, // 0 未开始 1 已开始 2 已结束
                    recordSrc: '', // 录音地址
                    time: 0, // 录音记录
                    rec: null,
                    recBlob: null,
                }
            },
            methods: {
                // 开始录音
                handleToStartRecord() {
                    if (rec && Recorder.IsOpen()) {
                        recBlob = null;
                        rec.start();
                        this.recordStatus = 1;
                    } else {
                        vant.showDialog({
                            title: '提示',
                            message: '请先授权使用麦克风功能!',
                        }).then(() => {
                            this.handleToOpenRecord();
                        });
                    };
                },
                // 停止录音
                handleToStopRecord() {
                    if (!(rec && Recorder.IsOpen())) {
                        vant.showToast('未打开录音!');
                        return;
                    };
                    rec.stop((blob, duration) => {
                        console.log(blob, (window.URL || webkitURL).createObjectURL(blob), "时长:" + duration + "ms");
                        recBlob = blob;
                        vant.showToast('录制成功!');
                        this.recordSrc = (window.URL || webkitURL).createObjectURL(recBlob);
                        this.recordStatus = 2;
                    }, (msg) => {
                        vant.showToast('录音失败!');
                        console.log("录音失败:" + msg);
                    });
                },
                // 重新录制
                handleToResetRecord() {
                    if (rec) {
                        rec.close();
                        this.recordStatus = 0;
                        document.querySelector('.timecount').innerText = '00:00:00'
                    } else {
                        vant.showToast('未打开录音!');
                    };
                },
                // 上传录音
                handleToUploadRecord() {
                    if (!this.group_id) {
                        return vant.showToast('请输入钉钉群链接!');
                    }
                    vant.showLoadingToast({
                        message: '上传文件中...',
                        forbidClick: true,
                    });
                    // 上传逻辑
                    let api = `https://edu.51cto.com/center/file/audio-summary/speech-text?group_id=${this.group_id}`;
                    let onreadystatechange = function (title) {
                        return function () {
                            if (xhr.readyState == 4) {
                                if (xhr.status == 200) {
                                    console.log(title + "上传成功", 2);
                                } else {
                                    console.log(title + "没有完成上传，演示上传地址无需关注上传结果，只要浏览器控制台内Network面板内看到的请求数据结构是预期的就ok了。", "#d8c1a0");

                                    console.error(title + "上传失败", xhr.status, xhr.responseText);
                                };
                            };
                        };
                    };
                    console.log("开始上传到" + api + "，请求稍后...");

                    let form = new FormData();
                    form.append("pcm_file", blob, "pcm_file");
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", api);
                    xhr.onreadystatechange = onreadystatechange("上传方式二【FormData】");
                    xhr.send(form);
                    setTimeout(() => {
                        vant.closeToast();
                        vant.showToast('上传成功!');
                    }, 2000);
                },
                // 打开录音
                handleToOpenRecord() {
                    this.rec = null;
                    this.recBlob = null;
                    this.newRec = Recorder({
                        type: "amr", sampleRate: 16000, bitRate: 16
                        , onProcess: (buffers, powerLevel, bufferDuration, bufferSampleRate, newBufferIdx, asyncEnd) => {
                            console.log(bufferDuration)
                        }
                    });
                    this.newRec.open(() => {
                        this.rec = this.newRec;
                    }, (msg, isUserNotAllow) => {
                        console.log(msg)
                        console.log(isUserNotAllow)
                    });
                },
                // 格式化时间
                formatTime(s) {
                    let h = 0;
                    let m = 0;
                    s = parseInt(s);
                    if (s >= 60) {
                        m = parseInt(s / 60);
                        s = parseInt(s % 60);
                        if (m >= 60) {
                            h = parseInt(m / 60);
                            m = parseInt(m % 60);
                        }
                    }
                    h = h < 10 ? '0' + h : h;
                    m = m < 10 ? '0' + m : m;
                    s = s < 10 ? '0' + s : s;
                    return `${h}:${m}:${s}`
                },
            }
        });
        app.use(vant);
        app.mount('#app');
    </script>
    <style>
        .main-box {
            background: #efefef;
            height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .timecount-box {
            margin-bottom: 10px;
        }
    </style>
</body>

</html>